<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { router } from "@/router";
import {
  task_search,
  addTask,
  task_detail,
  addRemoteTask,
  getTemplateList as getRemoteTemplateListAPI,
  getTaskTemplateList,
  task_search_remote,
  startWorkOrder,
  startRemoteWorkOrder,
  stopWorkOrder,
  stopRemoteWorkOrder,
  deleteTask,
  deleteRemoteTask,
} from "@/api/task";
import { message } from "@/utils/message";
import { copyTextToClipboard } from "@pureadmin/utils";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { useTaskForm } from "./useTaskForm";
import { createTableColumns } from "./helps";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { v4 as uuidv4 } from "uuid";
import AssetSyncDialog from "./components/AssetSyncDialog.vue";

defineOptions({
  name: "",
});

// 使用表单 hook
const {
  searchFormData,
  addTaskFormData,
  searchFormConfig,
  getAddTaskFormConfig,
  getViewTaskFormConfig,
  validateTaskForm,
  resetAddTaskForm,
  getSearchParams,
  getTemplateList,
  templateList,
} = useTaskForm();

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();
const addTaskFormRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const showAddTaskDialog = ref(false);
const modalFormData = ref<any>({});

// 资产同步弹窗相关
const showSyncDialog = ref(false);
const syncTaskName = ref("");
const syncTaskId = ref(0);

// 远程模板列表
const remoteTemplateList = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// API调用方法
const getAllTaskList = async (searchParam?: string) => {
  loading.value = true;
  try {
    const { data } = await task_search({
      search: searchParam || "",
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
    });

    if (data) {
      // tableData.value = transTarget(data.list);
      tableData.value = data.list;
      pagination.total = data.total || 0;
    }
  } catch (err) {
    console.error("获取任务列表失败:", err);
  } finally {
    loading.value = false;
  }
};

// 获取远程模板列表
const getRemoteTemplateList = async () => {
  try {
    const { data } = await getRemoteTemplateListAPI({
      search: "",
      pageIndex: 1,
      pageSize: 1000,
    });
    if (data && data.list) {
      remoteTemplateList.value = data.list.map((item: any) => ({
        label: item.name,
        value: item.id,
      }));
    }
  } catch (err) {
    console.error("获取远程模板列表失败:", err);
  }
};

const typeChange = async (type?: { type: string; row: any }) => {
  if (type?.type === "view") {
    const { data } = await task_detail({
      id: type.row.id,
    });
    modalFormData.value = {
      ...data,
      id: type.row.id,
    };
    showAddTaskDialog.value = true;
  } else if (type?.type === "sync-network") {
    // 打开资产同步弹窗
    syncTaskName.value = type.row.name;
    syncTaskId.value = type.row.id;
    showSyncDialog.value = true;
  } else {
    getAllTaskList();
  }
};

// 表格列配置 - 在 getAllTaskList 函数定义之后
const tableColumns = createTableColumns(typeChange);

const downloadData = (job_id: string) => {
  const anchor = document.createElement("a");
  anchor.href = "/api/asset_data/download?job_id=" + job_id;
  anchor.style.display = "none";
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
};

// 表单提交
const handleSearch = (value: any) => {
  getAllTaskList(value.search);
};

// 生成短UUID的函数
const generateShortUUID = () => {
  return uuidv4().replace(/-/g, "").substring(0, 8);
};

const handleAddTask = async (value: any) => {
  // 先进行表单验证
  if (!validateTaskForm(value)) {
    return;
  }
  const templateName = templateList.value.find(
    (item) => item.value === value.template
  )?.label;

  // 使用短UUID保证唯一性，缩短name长度
  const shortId = generateShortUUID();
  const params = {
    ...value,
    name: `${value.name}-${templateName}-${shortId}`,
    // 添加缺少的参数
    allNode: true,
    targetTp: "select",
    search: "",
    filter: {},
    targetNumber: 0,
    targetIds: [],
    project: [],
    targetSource: "general",
    bindProject: null,
    // 修改 week 参数
    week: 1, // 修改为 1
    // 删除多余的参数 transformButton
    node: ["node-test"],
    duplicates: "subdomain",
  };

  let firstTaskId = null;
  let secondTaskId = null;

  try {
    // 先执行第一个接口
    const firstResult = await addTask(params);
    firstTaskId = firstResult?.data?.id || (firstResult as any)?.id;

    // 再执行第二个接口
    const secondResult = await addRemoteTask({
      ...params,
      template: value.template2,
      duplicates: "None",
      cycleType: "daily",
      transformButton: undefined,
    });
    secondTaskId = secondResult?.data?.id || (secondResult as any)?.id;

    // 两个接口都成功
    ElMessage.success("添加成功");
    handleCancel();
    getAllTaskList();
  } catch (error) {
    // 有一个接口失败就会进入这里
    console.error("添加任务失败:", error);

    // 回滚成功的接口
    const rollbackPromises = [];
    if (firstTaskId) {
      rollbackPromises.push(deleteTask({ ids: [firstTaskId], delA: true }));
    }
    if (secondTaskId) {
      rollbackPromises.push(
        deleteRemoteTask({ ids: [secondTaskId], delA: true })
      );
    }

    if (rollbackPromises.length > 0) {
      try {
        await Promise.all(rollbackPromises);
        ElMessage.error("添加失败，已自动回滚");
      } catch (rollbackError) {
        console.error("回滚失败:", rollbackError);
        ElMessage.error("添加失败，且回滚失败，请手动处理");
      }
    } else {
      // 两个接口都失败了，不需要回滚
      ElMessage.error("添加失败");
    }
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getAllTaskList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getAllTaskList();
};

// 生命周期
onMounted(() => {
  getAllTaskList();
  getRemoteTemplateList();
  getTemplateList();
});

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  getAllTaskList();
};

const handleCancel = () => {
  showAddTaskDialog.value = false;
  addTaskFormRef.value?.resetFields();
  modalFormData.value = {
    isTransformed: false, // 确保有这个属性
  };
};

const handleOpenAddDialog = () => {
  modalFormData.value = {
    name: "",
    target: "",
    ignore: "",
    template: "",
    template2: "",
    scheduledTasks: false,
    cycleType: "",
    hour: 0,
    minute: 0,
    day: 1,
    week: 0,
    deduplicate: false,
    subdomainDeduplicate: false,
    scanTemplate: "",
    isTransformed: false,
  };
  showAddTaskDialog.value = true;
};

// 处理任务名称点击跳转
const handleTaskNameClick = (row: any) => {
  // 跳转到任务结果页面，与结果按钮保持一致
  router.push(`/taskmg/assetinfo?task=${row.name}`);
};

// 监听扫描类型变化，重置转换状态
watch(
  () => modalFormData.value.template,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      modalFormData.value.isTransformed = false;
    }
  }
);

// 监听扫描目标变化，重置转换状态
watch(
  () => modalFormData.value.target,
  (newValue, oldValue) => {
    if (
      newValue !== oldValue &&
      modalFormData.value.template === "684db9a5b02f85e29536da04"
    ) {
      modalFormData.value.isTransformed = false;
    }
  }
);
</script>

<template>
  <div>
    <el-card shadow="never">
      <!-- <template #header> -->
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          label-width="80px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
      <!-- </template> -->
    </el-card>

    <el-card shadow="never" class="mt-4">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="true"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleOpenAddDialog">
            新建任务
          </el-button>
        </template>
        <!-- 任务名称插槽 -->
        <template #taskName="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="handleTaskNameClick(row)"
            class="task-name-link"
          >
            {{ row.name }}
          </el-link>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 新建任务对话框 -->
    <el-dialog
      v-model="showAddTaskDialog"
      :title="modalFormData.id ? '查看任务' : '新建任务'"
      width="580px"
      destroy-on-close
      @close="handleCancel"
    >
      <DynamicForm
        ref="addTaskFormRef"
        v-model="modalFormData"
        :form-config="
          modalFormData.id
            ? getViewTaskFormConfig(modalFormData, remoteTemplateList)
            : getAddTaskFormConfig(modalFormData, remoteTemplateList)
        "
        label-width="140px"
        type="submit"
        @submit="handleAddTask"
        @cancel="handleCancel"
        :disabled="!!modalFormData.id"
      />
    </el-dialog>

    <!-- 资产同步弹窗 -->
    <AssetSyncDialog
      v-model="showSyncDialog"
      :task-name="syncTaskName"
      :task-id="syncTaskId"
      @close="showSyncDialog = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.el-btn-zese {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.el-btn-zese.is-disabled,
.el-btn-zese.is-disabled:focus,
.el-btn-zese.is-disabled:hover {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.task-name-link {
  font-weight: 500;
  cursor: pointer;

  &:hover {
    color: #409eff;
    text-decoration: underline;
  }
}
</style>
